import 'dart:async';
import 'dart:io';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:im_module/common/hexToColor.dart';
import 'package:im_module/common/message_cache_key.dart';
import 'package:im_module/global_context.dart';
import 'package:im_module/info/GroupInfoWidget.dart';
import 'package:im_module/manager/ImChatManager.dart';
import 'package:im_module/map/SelectMapAddressPage.dart';
import 'package:im_module/message/ShowMessageWidget.dart';
import 'package:im_module/model/LocationBean.dart';
import 'package:im_module/provider/im_provider.dart';
import 'package:im_module/widget/AdvanceMsgItem.dart';
import 'package:im_module/widget/AdvanceMsgList.dart';
import 'package:im_module/widget/AppBarBackground.dart';
import 'package:images_picker/images_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message.dart';

class ImChatWidget extends StatefulWidget {
  //1 单聊消息  2群消息
  int type;

  //如果是单聊是用户id 、如果是群聊则是群聊id
  String id;

  //如果是单聊是用户昵称 、如果是群聊则是群名字
  String? niceName;

  ImChatWidget({required this.type, required this.id, this.niceName});

  @override
  _ImChatWidgetState createState() => _ImChatWidgetState();
}

class _ImChatWidgetState extends State<ImChatWidget> {
  TextEditingController _controller = TextEditingController();
  ScrollController _scrollController = ScrollController();

  String _key = "";
  int page = 0;
  double tempPosition = 0.0;

  //是否加入了群聊
  bool isShowMore = false;

  @override
  void initState() {
    super.initState();
    if (widget.type == 1) {
      _key = MessageCacheKey.getC2cKey("${widget.id}");
    } else {
      _key = MessageCacheKey.getGroupKey("${widget.id}");

      //检测是否加入了这个群聊
      ImChatManager().checkGroupState("${widget.id}").then((value) {
        setState(() {
          isShowMore = value;
        });
      });

      //设置消息已读
      ImChatManager().markC2CMessageAsRead(widget.type, widget.id);
    }
  }

  @override
  void dispose() {
    Provider.of<ImProvider>(GlobalContext.getContext(), listen: false)
        .removeHistoryMessage(_key);
    if (widget.type == 2) {
      //设置消息已读
      ImChatManager().markC2CMessageAsRead(widget.type, widget.id);
    }
    super.dispose();
  }

  _controllerJumpTo() {
    Timer(Duration(milliseconds: 100), () {
      _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
    });
  }


  ///获取历史记录
  void getHistory(String? messageId) {
    ImChatManager()
        .getHistoryMessageList(_key, widget.type, widget.id, messageId);
  }

  Future<File?> getImageCompressPath(
      String imagePath, String targetPath) async {
    print("图片路径:$imagePath");
    print("保存图片路径:$targetPath");

    var result =
        await FlutterImageCompress.compressAndGetFile(imagePath, targetPath);
    return result;
  }

  Widget getAction() {
    if (widget.type == 1) {
      return Container();
    } else {
      return Offstage(
        offstage: !isShowMore,
        child: IconButton(
          onPressed: () async {
            bool result = await Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (ctx) =>
                        GroupInfoWidget(widget.id, "${widget.niceName}")));
            if (result) {
              Navigator.pop(context);
            }
          },
          icon: Icon(
            Icons.more_horiz,
            size: 28,
          ),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return AppBarBackground(
      child: Scaffold(
        backgroundColor: Colors.transparent,
        //backgroundColor: Color(0xfff2f2f2),
        resizeToAvoidBottomInset: true,
        appBar: AppBar(
          backgroundColor: Colors.transparent,
          title: Text("${widget.niceName}"),
          centerTitle: true,
          actions: [
            getAction(),
          ],
        ),
        body: Container(
          color: Color(0xfff2f2f2),
          child: GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              FocusScope.of(context).requestFocus(FocusNode());
            },
            child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                      child: Padding(
                    padding: const EdgeInsets.symmetric(vertical: 5),
                    child: ShowMessageWidget(widget.type, _key, widget.id),
                  )),
                  Container(
                    color: Colors.white,
                    padding: EdgeInsets.only(
                        left: 15,
                        right: 5,
                        bottom: MediaQuery.of(context).padding.bottom),
                    child: Row(
                      children: [
                        Expanded(
                          child: Container(
                            height: 50,
                            child: Container(
                              child: TextField(
                                controller: _controller,
                                decoration: InputDecoration(
                                  hintText: "输入您想说的话…",
                                ),
                                textInputAction: TextInputAction.send,
                                onSubmitted: (value) {
                                  if (value.isEmpty) {
                                    print("数据不能为空");
                                    return;
                                  }
                                  ImChatManager().sendMessage(
                                      widget.type, _key, widget.id, value);
                                  _controller.clear();
                                },
                              ),
                            ),
                          ),
                        ),
                        Container(
                            width: 56,
                            height: 50,
                            child: IconButton(
                              icon: Icon(Icons.add),
                              iconSize: 28,
                              onPressed: () {
                                FocusScope.of(context).requestFocus(FocusNode());
                                openPanel(context);
                              },
                            )),
                      ],
                    ),
                  )
                ]),
          ),
        ),
      ),
    );
  }

  Future? openPanel(context) {
    close() {
      Navigator.of(context).pop();
    }

    return showModalBottomSheet(
      context: context,
      builder: (ctx) {
        return Container(
          height: 130,
          color: hexToColor('ededed'),
          padding: EdgeInsets.all(15),
          child: GridView(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              childAspectRatio: 1,
              mainAxisSpacing: 15,
              crossAxisSpacing: 15,
            ),
            children: [
              new AdvanceMsgList(
                name: '相册',
                icon: Icon(
                  Icons.insert_photo,
                  size: 30,
                ),
                onPressed: () async {
                  close();
                  List<Media>? res = await ImagesPicker.pick(
                    count: 9,
                    pickType: PickType.image,
                  );
                  if (res == null || res.isEmpty) {
                    return;
                  }

                  Directory tempDir = await getTemporaryDirectory();
                  String tempPath = tempDir.path;

                  var rng = new Random(); //随机数生成类

                  res.forEach((element) {
                    var timenumber = DateTime.now().millisecondsSinceEpoch +
                        rng.nextInt(100);

                    String endWith = element.path.substring(
                        element.path.lastIndexOf('.'), element.path.length);

                    File newFile =
                        new File('${tempPath}/${timenumber}$endWith');

                    getImageCompressPath(element.path, newFile.absolute.path)
                        .then((value) => {
                              ImChatManager().sendImageMessage(_key,
                                  widget.type, widget.id, value?.absolute.path),
                            });
                  });
                },
              ),
              new AdvanceMsgList(
                name: '位置',
                icon: Icon(
                  Icons.map,
                  size: 30,
                ),
                onPressed: () async {
                  close();
                  LocationBean? result = await Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (ctx) => SelectMapAddressPage()));

                  if (result != null) {
                    ImChatManager().sendLocationMessage(
                        _key,
                        widget.type,
                        "${result.name}\n${result.address!}",
                        result.longitude,
                        result.latitude,
                        widget.id);
                  }
                },
              ),
            ].map((e) => AdvanceMsgItem(e)).toList(),
          ),
        );
      },
    );
  }

  Widget buildMessageBody(V2TimMessage message) {
    return Text("${message.sender}  ---- ${message.textElem?.toJson()}");
  }
}
